package com.etlmaster.executor.steps.loop;

import java.util.List;

import com.etlmaster.executor.EtlMasterExecutor;
import com.etlmaster.executor.EtlMasterException;
import com.etlmaster.executor.Job;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.StepStack;
import com.etlmaster.executor.steps.control.LoopStepInterface;
import com.etlmaster.executor.utils.StepState;

public class LoopStepMeta extends LoopStepInterface {

	public LoopStepMeta(String id, String name, String step_code,
			String session_id, String paramStr) {
		super(id, name, step_code, session_id, paramStr);
	}

	private String expression;


	public String getExpression() {
		return expression;
	}

	public void setExpression(String expression) {
		this.expression = expression;
	}

	@Override
	protected void loadParamsFromConfigTable() {
		// TODO Auto-generated method stub

	}

	@Override
	public int process(StepStack stack,StepMeta curStepMeta, Job job) {

		log("INFO", "Loop 开始执行步骤：{}", curStepMeta.getName());
		LoopProcessor loop = null;
		int result = StepState.RUNNING_SUCCESSED;
		if (expression != null) {
			if (expression.indexOf(";") > 0) {// 代表是普通循环 i=0;i<3;i++
				loop = new DefaultLoopProcessor();

				result = loop.loop(curStepMeta, job);
			} else if (expression.indexOf(" in ") > 0) {// 代表是游标 rs in select *
														// from
														// mk.bt_area@METADB
				loop = new SqlLoopProcessor();
				result = loop.loop(curStepMeta, job);
			} else if (expression.indexOf(" open ") > 0) {
				loop = new FileLoopProcessor();
				result = loop.loop(curStepMeta, job);
			}
		} else if (curStepMeta instanceof EndLoopStepMeta) {

			EtlMasterExecutor.handleStep(stack,curStepMeta, job);

		}
		if (result == StepState.RUNNING_SUCCESSED) {// endLoop(curStepMeta,
													// job);

		} else
			throw new EtlMasterException();
		return result;
	}
/*
	public void endLoop(StepStack stack,StepMeta curStepMeta, Job job)
			throws InterruptedException {
		if (curStepMeta instanceof EndLoopStepMeta) {
			EtlMasterExecutor.handleStep(stack,curStepMeta, job);
		} else {
			EtlMasterExecutor
					.startStep(stack,((LoopStep) curStepMeta.getStep())
							.getEndLoopNextSteps(job), job);
		}
	}
*/
	@Override
	public StepMeta getLoopNextStep(Job job) {
		List<StepMeta> result = job.getNextStepMetas(getId());
		return result.get(0);
	}

	@Override
	public List<StepMeta> getEndLoopNextSteps(Job job) {
		List<StepMeta> result = job.getNextStepMetas(getId());
		result.remove(0);
		return result;
	}

}
